題目有點長,縮了一點。
Given two arrays arr1 and arr2, return a new array joinedArray. All the objects in each of the two inputs arrays will contain an id field that has an integer value.
joinedArray is an array formed by merging arr1 and arr2 based on their id key. The length of joinedArray should be the length of unique values of id. The returned array should be sorted in ascending order based on the id key.
If a given id exists in one array but not the other, the single object with that id should be included in the result array without modification.
If a key is included in both objects, the value in the object from arr2 should override the value from arr1.
有兩個陣列arr1及arr2,傳回一個包含arr1及arr2的陣列。
如果兩個陣列具有相同的id,值不同時,則回傳陣列應將arr2覆蓋前值arr1。
如果arr1沒有arr2的值,回傳陣列應加列arr2。
第一次
var join = function(arr1, arr2) {
let result = {};
arr1.forEach(obj => {
result[obj.id] = obj;
});
arr2.forEach(obj => {
if (result[obj.id]){
result[obj.id].forEach(o => {
result[obj.id][o] = obj[o];
});
}
else {
result[obj.id] = obj;
}
});
return result;
};
先跑arr1,通通加入。
再跑arr2時判斷有沒有重複的。
但在result[obj.id].forEach()時發生錯誤,
result[obj.id]是一個物件,但不可以被遍歷。
這段的目的是為了將陣列裡的"值"取代,
因為無法判斷"值"是單個還是多個,
所以我們要先假設他是多個來處理。
要去尋找一個能夠取用arr的值,並且是能被遍歷的,
可以使用「Object.keys()」(回傳一個由指定物件所有可列舉之屬性組成的陣列)。
var join = function(arr1, arr2) {
let result = {};
arr1.forEach(obj => {
result[obj.id] = obj;
});
arr2.forEach(obj => {
if (result[obj.id]){
Object.keys(obj).forEach(o => {
result[obj.id][o] = obj[o];
});
}
else {
result[obj.id] = obj;
}
});
return result;
};
到這裡時,覺得應該大功告成了,
但秀出來的結果是:{"1":{"id":1,"x":1},"2":{"id":2,"x":9},"3":{"id":3,"x":5}}
這跟答案:[{"id":1,"x":1},{"id":2,"x":9},{"id":3,"x":5}],不一樣!
回頭再看一次題目:
return a new array joinedArray
回傳陣列而不是物件。
所以result應該轉成陣列,就可以使用「Object.values()」。
var join = function(arr1, arr2) {
let result = {};
arr1.forEach(obj => {
result[obj.id] = obj;
});
arr2.forEach(obj => {
if (result[obj.id]){
Object.keys(obj).forEach(o => {
result[obj.id][o] = obj[o];
});
}
else {
result[obj.id] = obj;
}
});
return Object.values(result);
};